package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"im/global"
	"im/model"
	"strconv"
)

type ChatHandler struct{}

func NewChatHandler() *ChatHandler {
	return &ChatHandler{}
}
func (h ChatHandler) Chat(context *gin.Context) {
	userId, err := strconv.Atoi(context.Query("userId"))
	if err != nil {
		return
	}
	conn, err := global.Upgrader.Upgrade(context.Writer, context.Request, nil)
	if err != nil {
		return
	}
	node := global.Node{
		Conn: conn,
		Data: make(chan []byte, 50),
	}
	global.CliMap[userId] = node
	go func(node global.Node) {
		for {
			_, message, err := node.Conn.ReadMessage()
			if err != nil {
				return
			}
			var msg model.Message
			err = json.Unmarshal(message, &msg)
			if err != nil {
				return
			}
			if n, ok := global.CliMap[msg.DistId]; ok {
				n.Data <- message
			}
		}
	}(node)
	go func(node global.Node) {
		for {
			data := <-node.Data
			err := node.Conn.WriteMessage(websocket.TextMessage, data)
			if err != nil {
				return
			}
		}
	}(node)
}
